import { login, logout } from '@/api/auth'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    id: '',
    name: '',
    role: [],
    token: getToken()
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_ID: (state, id) => {
    state.id = id
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_ROLE: (state, role) => {
    state.role = role
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  }
}

const actions = {
  /**
   * 登录系统
   * @param {*} context 上下文
   * @param {*} loginFrom 用户登录信息
   */
  login({ commit }, loginFrom) {
    return new Promise((resolve, reject) => {
      login(loginFrom).then(data => {
        commit('SET_ID', data.id)
        commit('SET_NAME', data.name)
        commit('SET_ROLE', data.role)
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  /**
   * 退出登录
   * @param {*} context 上下文
   */
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        removeToken()
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  /**
   * 刷新token
   * @param {*} context 上下文
   */
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken()
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

